<script setup lang="ts">

import MainLeftPanel from "./MainLeftPanel.vue";
import MainPanel from "./MainPanel.vue";
import {getCurrentInstance, onMounted, ref} from "vue";
import socket from "../socket/socket.ts";
import WindowContainer from "./WindowContainer.vue";
import { emit, listen } from '@tauri-apps/api/event'
import {useRootStore} from "../stores/root.ts";
import {storeToRefs} from "pinia";
import {login, setCookie} from "../api";
import {appWindow, UserAttentionType} from "@tauri-apps/api/window";

const mainPanel = ref()
const rootStore = useRootStore();
const {userInfo} = storeToRefs(rootStore);
const ctx = getCurrentInstance() as any
const snackVisible = ref(false)
const snackMsg = ref('')
const onActiveIndexChange = (index:number) =>{
  mainPanel.value.updateActiveIndex(index)
}

const onShowMessage = (message: string) => {
  showSnackBar(message)
}


let unlisten = null

const doLogin = (username:string,password:string)=>{
  socket.connect(username,password)
  login(username,password).then(res=>{
    if(res.data.code===200) {
      console.log(res)
      emit('LoginSuccess')
      appWindow.show()
      let cookie = res.headers['set-cookie']
      rootStore.updateCookie(cookie)
      setCookie(cookie)
      rootStore.updateUserInfo({
        avatar: res.data.data.avatar,
        name: res.data.data.name,
        userId: res.data.data.id
      })
      mainPanel.value.init()
    }else{
      emit('passwordError')
    }

  })
}

const showSnackBar=(msg:string)=>{
  snackMsg.value=msg;
  snackVisible.value=true
}


listen('login',(event:any)=>{
  doLogin(event.payload!.userId,event.payload!.password)
  
}).then(uls=>{
  unlisten = uls
})

socket.onOpen=()=>{
  console.log('connect')

}

socket.onMessage = (event:MessageEvent)=>{
  appWindow.requestUserAttention(UserAttentionType.Informational)
  let data = event.data;
  mainPanel.value.onMessage(JSON.parse(data))
}
</script>

<template>
  <window-container>
    <div class="main-frame" data-tauri-drag-region>
      <v-snackbar v-model="snackVisible" theme="">
        {{ snackMsg }}
      </v-snackbar>
      <main-left-panel 
        @activeIndexChange="onActiveIndexChange" 
        @showMessage="onShowMessage"
      ></main-left-panel>
      <main-panel ref="mainPanel"></main-panel>
    </div>
  </window-container>
</template>

<style scoped lang="scss">
.main-frame{

  height: 100%;
  display: flex;
  overflow: hidden;

}

</style>
